//
//  JCSubMDetailViewController.m
//  ERP
//
//  Created by QA on 15/11/13.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "JCSubMDetailViewController.h"

#import "WebServiceCommonRequest.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"
#import "RKTabView.h"
#import "JGActionSheet.h"
#import "EYInputPopupView.h"
#import "EYTextPopupView.h"
#import "NSKeyedArchiverUserLogin.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"
#import "AutoTextTableViewCell.h"
#import "JCSubMDetailViewCell.h"

@interface JCSubMDetailViewController ()

@property (nonatomic,strong) NSDictionary *contractBaseInfo;
@property (nonatomic,strong) NSMutableArray *subMBaseData;

@property (nonatomic,strong) NSArray *stateData;
@property (nonatomic,assign) NSInteger stateContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation JCSubMDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"采购申请单"];
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    self.stateData = [NSArray array];
    NSDictionary *dic = object;
    [self setShowInfoArray:dic];
}

- (void)setShowInfoArray:(NSDictionary*)dic
{
    self.contractBaseInfo = dic;
    NSInteger shztState = [self.contractBaseInfo objectFormatIntegerForKey:@"ZT"];
    
    NSMutableArray *subMBase = [NSMutableArray array];
    [self addContractInfoKey:@"编号" toKey:@"采购编号：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"项目名称" toKey:@"项目名称：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"购买方式" toKey:@"购买方式：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"申请人" toKey:@"申  请  人：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"申请时间" toKey:@"申请时间：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"申请站点" toKey:@"申请站点：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"状态" toKey:@"审核状态：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    
    if (shztState == 1) { //审核通过
        [self addContractInfoKey:@"审核人" toKey:@"审  核  人：" defaults:@"未知" format:nil form:dic toArray:subMBase];
        [self addContractInfoKey:@"审核时间" toKey:@"审核时间：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    } else if (shztState == 2){ //审核拒绝
        [self addContractInfoKey:@"审核人" toKey:@"审  核  人：" defaults:@"未知" format:nil form:dic toArray:subMBase];
        [self addContractInfoKey:@"审核时间" toKey:@"审核时间：" defaults:@"未知" format:nil form:dic toArray:subMBase];
        [self addContractInfoKey:@"拒绝原因" toKey:@"拒绝原因：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    }
    
    self.subMBaseData = subMBase;
    [self.tableView reloadData];
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取合同下近10单所有订单
    [self getJobstateInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 网络获取
- (void)getJobstateInfo
{
    //判断是否需要获取
    if(!self.contractBaseInfo) return;
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"FCGL_SQD_DETAILED"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    NSString *jobstate = [self.contractBaseInfo objectFormatStringForKey:@"TID"];
    [content addParameterKey:@"TID" value:jobstate];
    [content addParameterKey:@"起始条数" value:[NSNumber numberWithInteger:1]];
    [content addParameterKey:@"结束条数" value:[NSNumber numberWithInteger:200]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            self.stateData = [result.resultArray firstObject];
            self.stateContentState = self.stateData && self.stateData.count>0 ? 3 : 1;
        } else {
            self.stateContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
    }];
}


#pragma mark - 通用模板

- (void)drawExplainMarkView:(UIView*)contentView data:(NSArray*)data color:(NSArray*)color yValue:(CGFloat)yValue offset:(CGFloat)offset
{
    CGFloat itemWidth = contentView.frame.size.width / data.count - offset;
    for(int i=0; i<data.count; i++){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(offset*(i+1) + i*itemWidth, yValue, 15, 15)];
        view.backgroundColor = color[i];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 2.0;
        [contentView addSubview:view];
        
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(i*itemWidth + offset*(i+1) + 18, yValue + 2, itemWidth - 18, 10)];
        lable.text = data[i];
        lable.font = [UIFont systemFontOfSize:14];
        [contentView addSubview:lable];
    }
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        NSInteger shztState = [self.contractBaseInfo objectFormatIntegerForKey:@"ZT"];
        if (shztState == 0) return 2;
    } else if(section == 1) {
        if(self.stateContentState == 0) return 1;
        else if(self.stateContentState == 1) return 1;
        else if(self.stateContentState == 2) return 1;
        else if(self.stateContentState == 3) return self.stateData.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.subMBaseData];
        return cell;
        
    } else if(indexPath.section == 0 && indexPath.row == 1){
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier1";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSMutableArray *tabItems = [NSMutableArray array];//选项卡
        RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_favorite_highlighted"]];
        tabItem1.titleString = @"通过";
        tabItem1.titleFont = [UIFont systemFontOfSize:12];
        [tabItem1 addTarget:self selector:@selector(accreditSelector:)];
        [tabItems addObject:tabItem1];
        
        RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_keyboard_background_highlighted"]];
        tabItem2.titleString = @"拒绝";
        tabItem2.titleFont = [UIFont systemFontOfSize:12];
        [tabItem2 addTarget:self selector:@selector(refuseSelector:)];
        [tabItems addObject:tabItem2];
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
        [cell.contentView addSubview:lineView];
        return cell;
        
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.stateContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 26.5);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"没有采购清单";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载数据失败，点击重试";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            return cell;
            
        } else {
            NSString *identifier = [NSString stringWithFormat:@"JCSubMDetailViewCell"];
            JCSubMDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[JCSubMDetailViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            NSDictionary *mDictionary = [self.stateData objectAtIndex:indexPath.row];
            cell.sccjLabel.text = [mDictionary objectFormatStringForKey:@"生产厂家" defaults:@"未知"];
            cell.gydwLabel.text = [mDictionary objectFormatStringForKey:@"供应商" defaults:@"未知"];
            cell.jcsjLabel.text = [mDictionary objectFormatStringForKey:@"入库时间" defaults:@"未知"];
            cell.lxLabel.text = [mDictionary objectFormatStringForKey:@"分类" defaults:@"未知"];
            
            NSString *dw = [mDictionary objectFormatStringForKey:@"单位"format:@"元/%@" defaults:@""];
            NSString *dj = [mDictionary objectFormatFloatStringForKey:@"单价" retain:1];
            cell.djLabel.text = [NSString stringWithFormat:@"%@%@",dj,dw];
            
//            NSString *je = [mDictionary objectFormatFloatStringForKey:@"金额" retain:1];
//            NSString *sljeString = [NSString stringWithFormat:@"%@元",je];
            cell.jsslLabel.text = [mDictionary objectFormatFloatStringForKey:@"金额" retain:1 except:10000 exceptFormat:@"%@万元" format:@"%@元"];
            
            NSString *sl = [mDictionary objectFormatFloatStringForKey:@"数量" retain:0];
            NSString *mcge = [mDictionary objectFormatStringForKey:@"名称规格" defaults:@"未知"];
            cell.mcggLabel.text = [NSString stringWithFormat:@"%@ × %@",mcge,sl];
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"采购基本信息";
    } else if(section == 1){
        lable.text = @"采购物品清单";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.subMBaseData];
        return cell.contentView.frame.size.height;
        
    } else if(indexPath.section == 0 && indexPath.row == 1){
        return 48;
    } else if(indexPath.section == 1){
        if(self.stateContentState == 3) return 80;
        else return 55;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        if(self.stateContentState == 2) {//加载失败执行
            self.stateContentState = 0;
            [self.tableView reloadData];
            [self getJobstateInfo];
        } else if(self.stateContentState == 3){
            
        }
    }
}

#pragma mark 

//辅材审核--通过
- (void)accreditSelector:(id)sender
{
    [EYTextPopupView popViewWithTitle:@"辅材审核" contentText:@"您确认通过审核吗？" leftButtonTitle:@"取消" rightButtonTitle:@"通过" leftBlock:^() {
                                NSLog(@"left button clicked");
                           } rightBlock:^() {
                               //类型 1、通过  2、拒绝
                               NSLog(@"left button clicked");
                               [self applyOrderExamineAndVerifyType:1 reason:@""];
                           } dismissBlock:^() {
                             NSLog(@"Do something interesting after dismiss block");
                           }];
}


//辅材审核--拒绝
- (void)refuseSelector:(id)sender
{
    [EYInputPopupView popViewWithTitle:@"辅材审核" contentText:@"请输入拒绝原因" cancelButton:@"取消"
                              okButton:@"拒绝" type:EYInputPopupView_Type_multi_line
                           cancelBlock:^{
                            NSLog(@"left button cancel clicked");
                           } confirmBlock:^(UIView *view, NSString *text) {
                               //类型 1、通过  2、拒绝
                               NSLog(@"left button confirmBlock clicked");
                               [self applyOrderExamineAndVerifyType:2 reason:text];
                           } dismissBlock:^{
                               NSLog(@"left button dismiss clicked");
                           }];
}

//审核提交
- (void)applyOrderExamineAndVerifyType:(NSInteger)type reason:(NSString*)reason
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *Id = [self.contractBaseInfo objectFormatStringForKey:@"TID"];
    
    //类型 1、通过  2、拒绝
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setShowLoadingPrompt:self.navigationController labelText:@"提交审核中"];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"FCGL_SQD_AU"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"TID" value:Id];
    [content addParameterKey:@"类型" value:[NSNumber numberWithInteger:type]];
    [content addParameterKey:@"操作人" value:userInfo.username];
    [content addParameterKey:@"拒绝原因" value:reason];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0){
            firstArray = [result.resultArray firstObject];
        }
        //数据处理及显示
        [self verificationResultHandle:firstArray];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"提交失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"网络未连接"];
    }];
}

- (void)verificationResultHandle:(NSArray*)results
{
    if (results && results.count>0) {
        //提交成功
        [self showSuccessHUDText:@"提交成功"];
        NSDictionary *resultDictionary = [results firstObject];
        
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionaryWithDictionary:self.contractBaseInfo];
        [mDictionary setObject:[resultDictionary objectFormatStringForKey:@"状态"] forKey:@"状态"];
        [mDictionary setObject:[resultDictionary objectFormatIntegerNumberForKey:@"ZT"] forKey:@"ZT"];
        [mDictionary setObject:[resultDictionary objectFormatStringForKey:@"拒绝原因"] forKey:@"拒绝原因"];
        [mDictionary setObject:[resultDictionary objectFormatStringForKey:@"审核人"] forKey:@"审核人"];
        [mDictionary setObject:[resultDictionary objectFormatStringForKey:@"审核时间"] forKey:@"审核时间"];
        
        if(self.backResultDelagate)
        [self.backResultDelagate backResultDataKey:self.key dataValue:self.contractBaseInfo];
        [self setShowInfoArray:mDictionary];
        
    } else {
        //网络不畅
        [self showErrorHUDText:@"提交失败"];
    }
}

@end
